package cn.jasonone.bbs.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import cn.jasonone.bbs.bean.Article;
import cn.jasonone.bbs.bean.UserInfo;
import cn.jasonone.bbs.consts.ApplicationConsts;
import cn.jasonone.bbs.service.ArticleService;

@Controller
@RequestMapping("/article")
public class ArticleController implements ApplicationConsts {
	@Resource
	private ArticleService articleService;

	@GetMapping("/{articleId}")
	public String home(@PathVariable("articleId") Long articleId, ModelMap map) {
		Article article = articleService.findByID(articleId);
		map.put("article", article);
		return "article/article";
	}

	@GetMapping("/add")
	public String add() {
		return "article/addArticle";
	}

	@PostMapping("/add")
	public String add(Article article, @SessionAttribute(ApplicationConsts.LOGIN_STATUS_SESSION) UserInfo userInfo) {
		article.setCreatedBy(userInfo.getId());
		article.setAuthor(userInfo.getId());
		try {
			articleService.insert(article);
		} catch (Exception e) {
			e.printStackTrace();
			return "article/addArticle";
		}

		return "redirect:/article/" + article.getId();
	}
}
